package com.huitao.jpegdemo

import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

/**
 * author:huitao
 */
private const val TAG = "TestActivity"

class TestActivity : AppCompatActivity() {

    companion object {
        const val ACTION_USB_PERMISSION_BASE: String = "com.huitao.jpegdemo.USB_PERMISSION"
        private val ACTION_USB_PERMISSION = ACTION_USB_PERMISSION_BASE
        const val ACTION = "com.huitao.jpegdemo"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
    }

    private fun init() {
        mUsbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        register()

    }


    private lateinit var mPermissionIntent: PendingIntent
    private lateinit var mUsbManager: UsbManager
    private val handler = Handler(Looper.getMainLooper())


    private val getDeviceList = object : Runnable {
        override fun run() {
            Log.d(TAG, "run: 枚举设备")
            val deviceList = mUsbManager.deviceList
            Log.d(TAG, "run: ${deviceList.size}")
            val deviceValues = deviceList.values
            if (deviceValues.isNotEmpty()) {
                for (device in deviceValues) {
                    checkDevice(device)
                }
            }
            handler.postDelayed(this, 2000)
        }
    }

    private val mUsbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.d(TAG, "onReceive: " + intent?.action)
            when (intent?.action) {
                ACTION_USB_PERMISSION -> {
                    val permission =
                        intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                    Log.d(TAG, "onReceive: 获取权限结果:$permission")
                    if (permission) {
                        handler.removeCallbacks(getDeviceList)
                        val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                        val devicePermission = mUsbManager.hasPermission(device)
                        Log.d(TAG, "onReceive: ${device}")
                        Log.d(TAG, "onReceive: device permission = $devicePermission")
                        device?.let {
                            val pid = it.productId
                            val vid = it.vendorId
                            Log.d(TAG, "onReceive: uvc start  pid = $pid ,vid = $vid")
                            //   uvcjni.startUVC(pid, vid, 0)

                        }
                    }
                }

                UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                    Log.d(TAG, "onReceive: 设备插入")
                    val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                    Log.d(TAG, "onReceive:$device")
                    mUsbManager.requestPermission(device, mPermissionIntent)
                    handler.post(getDeviceList)
                }

                UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                    Log.d(TAG, "onReceive: 设备拔出")
                }

                ACTION -> {
                    Log.d(TAG, "onReceive: 接收到广播")
                }
            }

        }
    }

    @Synchronized
    fun register() {
        if (Build.VERSION.SDK_INT >= 34) {
//            val intent = Intent(ACTION_USB_PERMISSION)
//            intent.setPackage(ACTION)
            mPermissionIntent = PendingIntent.getBroadcast(
                this, 0, Intent(ACTION_USB_PERMISSION).apply {
                    setPackage(ACTION)
                    putExtra(UsbManager.EXTRA_PERMISSION_GRANTED,true)
                },
                FLAG_IMMUTABLE
            )
        } else if (Build.VERSION.SDK_INT >= 31) {
            val PENDING_FLAG_IMMUTABLE = 1 shl 25
            mPermissionIntent = PendingIntent.getBroadcast(
                this, 0, Intent(ACTION_USB_PERMISSION), PENDING_FLAG_IMMUTABLE
            )
        } else {
            mPermissionIntent =
                PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
        }
        val filter = IntentFilter()
        filter.addAction(ACTION_USB_PERMISSION)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
        //filter.addAction(ACTION)
        if (Build.VERSION.SDK_INT >= 34) {
            // RECEIVER_NOT_EXPORTED is required on Android 14
            // val RECEIVER_NOT_EXPORTED = 2
            registerReceiver(mUsbReceiver, filter, RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(mUsbReceiver, filter)
        }
        handler.post(getDeviceList)
    }

    private fun checkDevice(device: UsbDevice?) {
        if (device == null) {
            Log.d(TAG, "checkDevice: 设备为null")
            return
        }
        Log.d(TAG, "checkDevice: $device")
        if (!mUsbManager.hasPermission(device)) {
            Log.d(TAG, "checkDevice: 没有权限，请求权限")
            mPermissionIntent = PendingIntent.getBroadcast(
                this, 0, Intent(ACTION_USB_PERMISSION).apply {
                  //  setPackage(packageName)
                },
                PendingIntent.FLAG_IMMUTABLE
            )
            mUsbManager.requestPermission(device, mPermissionIntent)

        } else {
            Log.d(TAG, "checkDevice: 有权限")
            handler.removeCallbacks(getDeviceList)
        }

        if (device.deviceClass == UsbConstants.USB_CLASS_VIDEO) {
            Log.d(TAG, "checkDevice: 设备为USB_CLASS_VIDEO")
        } else {
            var isVideo = false
            for (i in 0 until device.interfaceCount) {
                val interfaceClass = device.getInterface(i).interfaceClass
                if (interfaceClass == UsbConstants.USB_CLASS_VIDEO) {
                    Log.d(TAG, "checkDevice: 设备为USB_CLASS_VIDEO")
                    isVideo = true
                    break
                }
            }
            if (!isVideo) {
                Log.d(TAG, "checkDevice: 其他设备")
            }

        }
    }
}